package com.coldwindblows.blog.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.coldwindblows.blog.bo.BackResponseBo;
import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.dto.LogActions;
import com.coldwindblows.blog.exception.TipException;
import com.coldwindblows.blog.pojo.OptionDo;
import com.coldwindblows.blog.service.ILogService;
import com.coldwindblows.blog.service.IOptionService;
import com.coldwindblows.blog.service.ISiteService;

/**
 * Created by ColdWindBlows on 2018/07/07
 *
 */
@Controller
@RequestMapping("/admin/setting")
@SuppressWarnings("rawtypes")
public class SettingController extends BaseController {

	@Autowired
	private IOptionService optionService;
	
	@Autowired
	private ILogService logService;
	
	@Autowired
	private ISiteService siteService;
	
	/**
	 * 系统设置
	 * @param model
	 * @return
	 */
	@GetMapping("")
	public String setting(Model model) {
		List<OptionDo> list = optionService.getOptions();
		Map<String, String> options = new HashMap<>();
		list.forEach(option -> {
			options.put(option.getName(), option.getValue());
		});
		
		if(options.get("site_record") == null) {
			options.put("site_record", "");
		}
		model.addAttribute("options", options);
		return "admin/setting";
	}
	
	@PostMapping("")
	@ResponseBody
	public RestResponseBo saveSetting(@RequestParam(required = false) String site_theme, HttpServletRequest request) {
		try {
			Map<String, String[]> parameterMap = request.getParameterMap();
			Map<String, String> querys = new HashMap<>();
			parameterMap.forEach((key, value) -> {
				querys.put(key, join(value));
			});
			optionService.insertOptions(querys);
			WebConst.initConfig = querys;
			if(StringUtils.isNotBlank(site_theme)) {
				BaseController.THEME = "themes/" + site_theme;
			}
			logService.insertLog(LogActions.SYS_SETTING.getAction(), JSON.toJSONString(querys), request.getRemoteAddr(), this.getUid(request));
			return RestResponseBo.ok();
		} catch(Exception e) {
			String msg = "保存设置失败";
			return RestResponseBo.fail(msg);
		}
	}
	
	@PostMapping("/backup")
	@ResponseBody
	public RestResponseBo backup(String bk_type, String bk_path, HttpServletRequest request) {
		if(StringUtils.isBlank(bk_type)) {
			return RestResponseBo.fail("请确认信息输入完整");
		}
		try {
			@SuppressWarnings("unused")
			BackResponseBo backResponse = siteService.backup(bk_type, bk_path, "yyyyMMddHHmm");
			logService.insertLog(LogActions.SYS_BACKUP.getAction(), null, request.getRemoteAddr(), this.getUid(request));
			return RestResponseBo.ok();
			
		} catch (Exception e) {
			String msg = "备份失败";
			if(e instanceof TipException) {
				msg = e.getMessage();
			}
			return RestResponseBo.fail(msg);
		}
	}
	
	/**
	 * 数组转字符串
	 * @param arr
	 * @return
	 */
	private String join(String[] arr) {
		StringBuilder ret = new StringBuilder();
		int len = arr.length;
		
		for(int i = 0; i < len; i++) {
			ret.append(",").append(arr[i]);
		}
		
		return ret.length() > 0 ? ret.substring(1) : ret.toString();
	}
}
